<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\common\model;

use buwang\base\TimeModel;
use buwang\traits\ModelTrait;

class UserBill extends TimeModel
{
    use ModelTrait;

    protected $name = "user_bill";

    protected $deleteTime = false;


    /**
     * 累计充值
     */
    public static function getRecharge($uid)
    {
        return self::where('uid', $uid)
            ->where('category', 'money')
            ->where('type', 'recharge')
            ->where('pm', 1)
            ->where('status', 1)
            ->sum('number');
    }

    //出账记录
    public static function expend($title, $uid, $category, $type, $number, $link_id = 0, $balance = 0, $mark = '', $status = 1)
    {
        $pm = 0;
        $add_time = time();
        return self::create(compact('title', 'uid', 'link_id', 'category', 'type', 'number', 'balance', 'mark', 'status', 'pm', 'add_time'));
    }

    //入账记录
    public static function income($title, $uid, $category, $type, $number, $link_id = 0, $balance = 0, $mark = '', $status = 1)
    {
        $pm = 1;
        $add_time = time();
        return self::create(compact('title', 'uid', 'link_id', 'category', 'type', 'number', 'balance', 'mark', 'status', 'pm', 'add_time'));
    }


    public function user()
    {
        return $this->belongsTo('\app\common\model\User', 'uid', 'id');
    }


    public function getUserList($memberId = 0)
    {
        $self = new User;
        if ($memberId) {
            $ids = MemberMiniapp::where('member_id', $memberId)->column('id');
            if ($ids) {
                $self = $self->where('member_miniapp_id', 'in', $ids);
            }
        }
        return $self->column('nickname', 'id');
    }

    public function getPmList()
    {
        return ['0' => '支出', '1' => '获得',];
    }

    public function getCategoryList()
    {
        return ['money' => '余额', 'integral' => '积分'];
    }

    public function getTypeList($memberId = 0, $category = null)
    {
        $self = new self;
        $self = $self->join('bw_user user', 'uid=user.id', 'LEFT');
        $data = [];
        if ($category) $self = $self->where('category', 'in', $category);
        if ($memberId) {
            $ids = MemberMiniapp::where('member_id', $memberId)->column('id');
            if (!$ids) return $data;
            $self = $self->where('user.member_miniapp_id', 'in', $ids);
        }
        $list = $self->field(['title', 'type'])
            ->group('type')
            ->distinct(true)
            ->select()
            ->toArray();
        if ($list) {
            foreach ($list as $value) {
                $data[$value['type']] = $value['title'];
            }
        }

        return $data;
    }

    public function getStatusList()
    {
        return ['0' => '待确认', '1' => '有效', '-1' => '无效',];
    }

    /**得到租户所有应用
     * @return array
     */
    public function getMemberMiniappList($member_id = 0)
    {
        $MemberMiniapp = new \app\common\model\MemberMiniapp;
        if ($member_id) $MemberMiniapp = $MemberMiniapp->where('member_id', $member_id);

        return $MemberMiniapp->column('appname', 'id');
    }

//    /**
//     * @return \think\model\relation\BelongsTo
//     */
//    public function memberMiniapp()
//    {
//        return $this->belongsTo('\app\manage\model\MemberMiniapp', 'member_miniapp_id', 'id');
//    }


    /**
     * 获取用户账单明细
     * @param int $uid 用户uid
     * @param int $page 页码
     * @param int $limit 展示多少条
     * @param int $type 展示类型
     * @param int $type 记录的币种
     * @return array
     * */
    public static function getUserBillList($uid, $page, $limit, $type, $category = '')
    {
        if (!$limit) return [];
        //根据年月分组查询出每个时间段的账单记录，筛出记录年月和记录的ids（记录id去重并用逗号合并成一个字符串ids）
        $model = self::where('uid', $uid)->order('add_time desc')->where('number', '<>', 0)
            ->field('FROM_UNIXTIME(add_time,"%Y-%m") as time,group_concat(DISTINCT id ORDER BY id DESC SEPARATOR ",") ids')->group('time');
        if ($category) $model = $model->where('category', 'in', $category);
        //不同记录条件
        switch ((int)$type) {
            case 0://全部

                break;
            case 1: //消费
                $model = $model->where('type', 'pay_product');
                break;
            case 2: //转换
                $model = $model->where('type', 'in', 'change_money');
                break;
            case 3: //返佣
                $model = $model->where('type', 'brokerage,brokerage_two');
                break;

        }
        if ($page) $model = $model->page((int)$page, (int)$limit);
        $list = ($list = $model->select()) ? $list->toArray() : [];
        $data = [];
        foreach ($list as $item) {
            $value['time'] = $item['time'];
            //查询该时间段内的所有记录数据
            $value['list'] = self::where('id', 'in', $item['ids'])->field('FROM_UNIXTIME(add_time,"%Y-%m-%d %H:%i") as add_time,title,number,mark,pm')->order('add_time DESC')->select();
            array_push($data, $value);
        }
        return $data;
    }

}